#include "core.h"
#include "MapMgr.h"
#include "Map.h"
#include "../engine/xLevelMgr.h"
#include "GlobalConfig.h"

//---------------------------------------------------------------------------------------------
IMP_SINGLETON_CLASS( CResourceMgr )

CResourceMgr::CResourceMgr()
{
	m_mapMgr = new CMapMgr;
}

CResourceMgr::~CResourceMgr()
{
	if (m_mapMgr)
	{
		delete m_mapMgr;
	}
}

CMap* CResourceMgr::getMap(UINT map_id)
{
	if (m_mapMgr)
	{
		return m_mapMgr->getMapById(map_id);
	}

	return NULL;
}

void CResourceMgr::Init()
{
	CLevelMgr* pLevelMgr = CLevelMgr::getInstance();

	for(LevelList::iterator it = pLevelMgr->m_mapLevels.begin(); it != pLevelMgr->m_mapLevels.end(); ++it)
	{
		LevelAttr* pLA = it->second;
		if (pLA->eLevelMainType == LMT_GATE)
		{
			UINT nSenceID = pLA->nSenceID;
			m_mapMgr->addMap(nSenceID);
		}
	}
}

//---------------------------------------------------------------------------------------------
CMapMgr::CMapMgr()
{

}

CMapMgr::~CMapMgr()
{

}

void CMapMgr::addMap( U32 map_id )
{
	CResourceMgr* rs_mgr = CResourceMgr::getInstance();

	CMap* pMemMap = NULL;
	CMap * map = new CMap();
	if (rs_mgr)
	{
		pMemMap = rs_mgr->getMap(map_id);
	}
	if (pMemMap)
	{
		*map = *pMemMap;
	}
	else
	{
		boost::filesystem::path map_dir = CClobalConfigMgr::getInstance()->getAppPath();
		map_dir = map_dir / "../map";
	
		std::string str_map_id;
		std::string str_map_id_back = "9999"; ///< ugly
		{
			CHAR number[200];
			sprintf( number, "%d", map_id );
			str_map_id = number;
		}

		boost::filesystem::path map_path_back = map_dir / str_map_id_back ;
		map_path_back.normalize();
		boost::filesystem::path map_npc_back = map_dir / str_map_id_back;
		map_npc_back.normalize();
		boost::filesystem::path map_grid = map_dir / str_map_id ;
		map_grid.normalize();
		std::string map_npc_file_back = map_npc_back.string();
		map_npc_file_back += "npc.json";
		boost::filesystem::path map_path = map_dir / str_map_id ;
		map_path.normalize();
		boost::filesystem::path map_npc = map_dir / str_map_id;
		map_npc.normalize();
		std::string map_npc_file = map_npc.string();
		map_npc_file += "npc.json";
		std::string map_grid_file = map_grid.string();
		map_grid_file += "_grid.json";
		if(!boost::filesystem::exists(map_npc_file))  map_npc_file=map_npc_file_back;
		map->LoadMap( map_id, map_npc_file);

		if(boost::filesystem::exists(map_grid_file))
		{
			map->LoadGrid(map_grid_file);
		}
	}

	std::pair<MapList::iterator, bool> ins = m_mapList.insert(MapList::value_type(map_id, map));
	if (!ins.second)
	{
		delete map;
	}
}

CMap *CMapMgr::getMapById( UINT map_id )
{
	MapList::iterator it = m_mapList.find(map_id);
	if (it != m_mapList.end())
	{
		return it->second;
	}
	return NULL;
}